// 购物车案例 useReducer hook应用

import { useReducer, useEffect } from "react";
import db from "../../utils/db2";

const initData = [
  { name: "小明(只)", price: 100, count: 1, id: 1, isEdit: false },
  { name: "中明(只)", price: 200, count: 1, id: 2, isEdit: false },
  { name: "大明(只)", price: 300, count: 1, id: 3, isEdit: false }
];

type StateData = typeof initData;

interface Action {
  type: "ADD" | "SUB" | "EDIT" | "DELETE" | "UPDATE_NAME";
  id: number;
  newName?: string;
}

const reducer = (shopList: StateData, action: Action) => {
  const item = shopList.find((item) => item.id === action.id)!;
  switch (action.type) {
    case "ADD":
      item.count++;
      return [...shopList];
    case "SUB":
      item.count--;
      return [...shopList];
    case "EDIT":
      item.isEdit = !item.isEdit;
      return [...shopList];
    case "DELETE":
      return shopList.filter((item) => item.id !== action.id);
    case "UPDATE_NAME":
      item.name = action.newName!;
      return [...shopList];
    default:
      return shopList;
  }
};

function App() {
  const [shopList, dispatch] = useReducer(reducer, initData);

  useEffect(() => {
    const fetchData = async () => {
      try {
        await db.TransferStore.add({ key: "abc", bankType: "def" });
        // const res = await MyDB.AppStore.get("shopList");
        // if (!res) {
        //   await MyDB.AppStore.add({ key: "shopList", value: initData });
        // } else {
        //   MyDB.AppStore.update("shopList", {
        //     value: shopList
        //   });
        // }
      } catch (error) {
        console.log(error);
      }
    };
    fetchData();
  }, [shopList]);
  return (
    <>
      <table cellSpacing={0} cellPadding={10} border={1} width={600}>
        {/* 表头 */}
        <thead>
          <tr>
            <th>商品名称</th>
            <th>商品价格</th>
            <th>商品数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {shopList.map((item) => {
            return (
              <tr key={item.id}>
                <td align="center">
                  {item.isEdit ? (
                    <input
                      type="text"
                      value={item.name}
                      onChange={(e) =>
                        dispatch({
                          type: "UPDATE_NAME",
                          id: item.id,
                          newName: e.target.value
                        })
                      }
                      onBlur={() => dispatch({ type: "EDIT", id: item.id })}
                    />
                  ) : (
                    item.name
                  )}
                </td>
                <td align="center">{item.price}</td>
                <td
                  align="center"
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: "10px"
                  }}
                >
                  <button
                    onClick={() => dispatch({ type: "SUB", id: item.id })}
                  >
                    -
                  </button>
                  {item.count}
                  <button
                    onClick={() => dispatch({ type: "ADD", id: item.id })}
                  >
                    +
                  </button>
                </td>
                <td align="center">
                  <button
                    onClick={() => dispatch({ type: "EDIT", id: item.id })}
                    style={{ marginRight: "10px" }}
                  >
                    编辑
                  </button>
                  <button
                    onClick={() => dispatch({ type: "DELETE", id: item.id })}
                  >
                    删除
                  </button>
                </td>
              </tr>
            );
          })}
        </tbody>
        <tfoot>
          <tr>
            <td align="center" colSpan={4}>
              总价：
              {shopList.reduce((pre, cur) => pre + cur.price * cur.count, 0)}
            </td>
          </tr>
        </tfoot>
      </table>
    </>
  );
}

export default App;
